import {Component, OnInit, AfterViewInit, ViewChild} from '@angular/core';
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../util/response-util";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {TableUtil} from "../../../util/table-util";
import {API, MsgConstants} from "../../../constants/constants";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {ExceptionService} from "./exception.service";
import {MsgResult} from "../../../models/msg-result";

declare var $;
declare var moment;
@Component({
  selector: 'app-exception',
  templateUrl: './exception.component.html',
  styleUrls: ['./exception.component.css']
})
export class ExceptionComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;

  table;
  config;
  config2;

  exceptionIdArr : Array<string> = [];
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private exceptionService: ExceptionService,
    private dialogService: OneDialogService,
    private response: ResponseUtil
  ) { }

  ngOnInit() {
    this.initTime();
    //初始化面包屑导航
    this.pushPage();
    //初始化表单
    this.loadLoginLog();

  }  //end ngOnInit

  proxy = {
    "exceptionLogDetails": () => this.exceptionLogDetails(),
    "exceptionLogDelete": () => this.exceptionLogDelete()
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("系统日志", "");
    this.pageSubject.pushPage("系统日志", "异常日志查询", path);
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  loadLoginLog() {
    this.table = this.tableUtil.load("one_table_excLog",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "operName", title: '操作者名称',class:"one-bs-width-6", align: 'left'},
        {field: "moduleName", title: '模块名',class:"one-bs-width-4", align: 'left'},
        {field: "type", title: '类型',class:"one-bs-width-2", align: 'left',formatter: this.typeFormat},
        {field: "className", title: '操作类名',class:"one-bs-width-4", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "methodName", title: '操作方法名',class:"one-bs-width-6", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "content", title: '异常日志内容',class:"one-bs-width-6", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "OPERATE_TIME", title: '操作时间',class:"one-bs-width-4", align: 'left', sortName: "OPERATE_TIME", sortable: true,formatter: this.tableUtil.showToolTip},
        {field: "ip", title: 'ip',class:"one-bs-width-4", align: 'left',formatter: this.tableUtil.showToolTip},
        {field: "params", title: '参数',class:"one-bs-width-2", align: 'left', visible: false},
        {field: "exceptionName", title: '异常名称',class:"one-bs-width-4", align: 'left',formatter: this.tableUtil.showToolTip}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: false,//多选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_exception",
      url: API.excLogPageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.operName = $("#operName").val();
        params.startTime =  $("#startTime").val();
        params.endTime = $("#endTime").val();
        console.log(params);
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.OPERATE_TIME = value.operTime || '';
          });
        });
      },
      height: 700,//table高度
      sortable: true,
      sortOrder: 'desc',
      sortName: 'OPERATE_TIME',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);
  }

  typeFormat(value, row, index) {
    if (value == '1') {
      return '新增';
    }
    if (value == '2') {
      return '修改';
    }
    if (value == '3') {
      return '删除';
    }
    if (value == '4') {
      return '查询';
    }
  }

  //初始化日期插件
  initTime(){
    // let timeData = moment().format("YYYY-MM-DD HH:mm:ss");
    // let startDate = moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss");

    this.config = {
      timePicker:true,
      timePickerIncrement:1,
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      maxDate:moment().format("YYYY-MM-DD HH:mm:ss"),
      locale:{
        format:"YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      // startDate: moment().subtract(7, "days").format("YYYY-MM-DD HH:mm:ss"),
      startDate: moment().add(5,'m').subtract(1,"days").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().add(5,'m').format("YYYY-MM-DD HH:mm:ss")
    };


    this.config2 = {
      timePicker:true,
      timePickerIncrement:1,
      singleDatePicker: true,
      timePicker24Hour:true,
      parentEl:$(".wrapper"),
      // maxDate:timeData,
      locale:{
        format:"YYYY-MM-DD HH:mm:ss",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: moment().add(5,"m").format("YYYY-MM-DD HH:mm:ss"),
      endDate: moment().add(5,"m").format("YYYY-MM-DD HH:mm:ss")
    };

    $("#startTime").daterangepicker(this.config);
    $("#endTime").daterangepicker(this.config2);
  }

  /**
   * 查询单条日志详情
   */
  exceptionLogDetails(){
    let row = this.table.bootstrapTable('getSelections');
    this.exceptionIdArr = this.tableUtil.getIds(row);
    console.log(JSON.stringify(this.exceptionIdArr));
    if(this.exceptionIdArr.length != 1){
      this.dialogService.modalInfo('请选择一条数据！');
    }else {
      this.router.navigate(['exception-detail',{id:this.exceptionIdArr[0]}],{relativeTo:this.route});
    }
  }

  /**
   * 批量删除日志时：
   * 1.判断勾选是否为空
   */
  exceptionLogDelete(){
    let rows = this.table.bootstrapTable('getSelections');
    this.exceptionIdArr = this.tableUtil.getIds(rows);
    if(this.exceptionIdArr.length == 0){
      this.dialogService.modalInfo('请选择一条数据！');
    }else {
      this.dialogService.modalInfoWithCancelBtn('确定删除？',this.deleteExceptionLog);
    }
  }

  /**
   *  1.调用后台接口
   *  2.对结果进行处理
   */
  private deleteExceptionLog=()=>{
    this.exceptionService.exceptionLogDelete(this.exceptionIdArr).subscribe(
        result => this.response.success(result,this.processExceptionLogResult),
        error => this.response.error(error)
    );
  }

  /**
   * 对结果进行判断并进行处理
   * @param {MsgResult} result
   */
  private processExceptionLogResult =(result:MsgResult)=>{
    if(result && result.code == MsgConstants.MSG_CODE_OK){
        this.dialogService.success(result.message);
        this.search();
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
        this.dialogService.error(result.message);
    }
  }

}
